package com.dataseek.iot.sys.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dataseek.iot.sys.entity.WorkLine;
import com.dataseek.iot.sys.service.DbService;
import com.dataseek.iot.sys.service.WorkLineService;
import com.dataseek.iot.sys.vo.WorkLineVo;
import com.dataseek.iot.toolikit.common.enums.RspStatusEnum;
import com.dataseek.iot.toolikit.common.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("**/workLine")
public class WorkLineController {

    @Autowired
    private WorkLineService workLineService;

    @Autowired
    private DbService dbService;

    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ResponseResult query(@RequestParam(value="page")  Integer page,
                                      @RequestParam(value="size")  Integer size,
                                      @RequestParam(value="lineName", required=false) String lineName,
                                      @RequestParam(value="open", required=false)  String open) throws IOException {
        WorkLineVo tenantVo = workLineService.queryAction(lineName,open,page,size);
        return new ResponseResult(RspStatusEnum.SUCCESS.getCode(),"成功",tenantVo);
    }


    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public ResponseResult insert(@RequestBody WorkLine workLine) throws IOException {
        Integer code  = workLineService.insertAction(workLine);
        ResponseResult responseResult = null;
        if (code == RspStatusEnum.FAIL.getCode()) {
            responseResult=new ResponseResult(RspStatusEnum.FAIL.getCode(),"产线名称或编码重复，请重新输入!",code.toString());
        } else {
            responseResult=new ResponseResult(RspStatusEnum.SUCCESS.getCode(),"成功!",code.toString());
        }
        return responseResult;
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseResult update(@RequestBody WorkLine workLine) throws IOException {
        Integer code  = workLineService.updateAction(workLine);
        return new ResponseResult(RspStatusEnum.SUCCESS.getCode(),RspStatusEnum.SUCCESS.getMessage(),code.toString());
    }


    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseResult delete(@RequestBody JSONObject ids)  throws IOException {
        JSONArray jsonArray = ids.getJSONArray("ids");
        List<Integer> listIds = JSONObject.parseArray(jsonArray.toJSONString(), Integer.class);
        Integer code  = workLineService.deleteAction(listIds);
        return new ResponseResult(RspStatusEnum.SUCCESS.getCode(),RspStatusEnum.SUCCESS.getMessage(),code.toString());
    }

}
